package com.okwanshiwu.payment.aliUtil;

import com.alipay.api.response.AlipayTradeQueryResponse;
import com.okwanshiwu.payment.common.AbstractPayType;
import com.okwanshiwu.util.SignUtils;
import org.apache.log4j.Logger;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Map;

/**
 * 阿里订单信息实现类
 *
 * @author master
 * @create 2017-07-31 11:12
 **/
public class AlipayType extends AbstractPayType {

	private Logger logger = Logger.getLogger(AlipayType.class);

	@Override
	public String orderInfo(String orderId, int price, String content, Map<String, String> other){
		AliProperties aliProperties = new AliProperties(content,content,price,orderId);
		String orderInfo = AliPayUtil.createOrderInfo(aliProperties);//生成订单信息
		String sign = SignUtils.sign(orderInfo,AliProperties.RSA_PRIVATEOWN);//生成签名串
		try {
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			logger.error("不支持此种编码格式！！！");
		}
		String payInfo = orderInfo + "&sign=\"" + sign + "\"&sign_type=\"RSA\"";
		return payInfo;
	}

	/**
	 * 查询订单状态（不验证金额）
	 * @param orderId 商户订单号
	 * @return
	 */
	@Override
	public boolean getOrderResult(String orderId) {
		AlipayTradeQueryResponse response = AliPayUtil.orderResult(orderId);
		if(response != null){
			return true;
		}
		return false;
	}
	/**
	 * 查询订单状态（验证金额）
	 * @param orderId 商户订单号
	 * @param price 订单价格 单位为分
	 * @return
	 */
	@Override
	public boolean getOrderResult(String orderId, int price) {
		AlipayTradeQueryResponse response = AliPayUtil.orderResult(orderId);
		if(response != null){
			String totalAmount = response.getTotalAmount();
			BigDecimal orderPrice = new BigDecimal(totalAmount==null?"0":totalAmount);
			int totalPrcie = orderPrice.multiply(new BigDecimal("100")).intValue();
			return price == totalPrcie?true:false;
		}
		return false;
	}


	@Override
	public String refundOrder(String refundId, String orderId) {
		return null;
	}


}
